package com.example.h5server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.h5server.model.User;
import com.example.h5server.repository.UserMapper;

import com.example.h5server.service.LoginAuthService;
import com.example.h5server.utils.JwtUtils;
import com.example.h5server.utils.Result;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class LoginAuthServiceImpl implements LoginAuthService {

    private final UserMapper userMapper;
    private final JwtUtils jwtUtils;
    private static final Logger logger = LoggerFactory.getLogger(LoginAuthServiceImpl.class);

    public LoginAuthServiceImpl(UserMapper userMapper, JwtUtils jwtUtils, UserServiceImpl userServiceImpl) {
        this.userMapper = userMapper;
        this.jwtUtils = jwtUtils;

    }

    /**
     * 用户登录验证并返回结果
     * @param username 用户名
     * @param password 密码
     * @return 登录结果，包含用户信息和token
     */
    public Result<LoginResponse> login(String username, String password) {
        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (password == null || password.isEmpty()) {
            return Result.error("密码不能为空");
        }

        User user = userMapper.selectList(new QueryWrapper<User>().eq("username", username)).stream().findFirst().orElse(null);
        if (user == null) {
            return Result.error("用户不存在");
        }
//        logger.info("找到用户: {}, 用户ID: {}", user.getPassword(), user.getPassword());
        // 验证密码逻辑
        boolean isAuthenticated = false;

        if ("superAdmin".equals(username)) {

            // `superAdmin` 直接明文对比
            isAuthenticated = password.equals(user.getPassword());
        } else {
            // 其他用户使用BCrypt加密验证
            isAuthenticated = checkPassword(password, user.getPassword());
        }

        if (isAuthenticated) {
            // 生成JWT `token`
            String token = jwtUtils.generateToken(user.getId());
            LoginResponse response = new LoginResponse(user, token);
            return Result.success("登录成功", response);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    /**
     * 密码验证方法
     * @param rawPassword 明文密码
     * @param encodedPassword 加密密码
     * @return 验证结果
     */
    private boolean checkPassword(String rawPassword, String encodedPassword) {
        try {
            return BCrypt.checkpw(rawPassword, encodedPassword);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 登录响应数据类
     */
    public static class LoginResponse {
        private User user;
        private String token;

        public LoginResponse() {} // 默认构造函数

        public LoginResponse(User user, String token) {
            this.user = user;
            this.token = token;
        }

        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }
    }
}
